package com.hand.wfive.loginAndVip.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import com.hand.wfive.R
import com.hand.wfive.activity.PrivacyActivity
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.MD5Util
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.model.CodeLoginModel
import com.hand.wfive.util.SharedPreferencesUtils
import com.hand.wfive.util.click.NoFastClickUtils
import com.qmuiteam.qmui.widget.QMUITopBarLayout
import com.rxjava.rxlife.RxLife
import kotlinx.android.synthetic.main.login_activity_login_code.*
import rxhttp.wrapper.param.RxHttp
import kotlin.random.Random

@SuppressLint("SetTextI18n")
class LoginCodeActivity : LoginBaseActivity() {

    private var mTime = 0L
    private var mCode = ""
    private var mMobile = ""
    private lateinit var mSpUtils: SharedPreferencesUtils
    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {
        fun start() {
            sendEmptyMessageDelayed(0x101, 1000)
        }

        fun stop() {
            removeMessages(0x101)
        }

        override fun handleMessage(msg: Message) {
            val time = (System.currentTimeMillis() - mTime) / 1000
            println("time=$time")
            if (time >= 60) {
                mTime = 0L
                login_code_get.isEnabled = true
                login_code_get.text = "获取验证码"
            } else {
                login_code_get.text = "${60 - time}s后重新获取"
                start()
            }
        }
    }

    override fun getContentViewId() = R.layout.login_activity_login_code

    override fun init() {
        initLogin()
        tvWelcome.text = "欢迎登录${getString(R.string.app_name)}"
        // 数据缓存
        mSpUtils = SharedPreferencesUtils(this, "LoginCodeW")
        mMobile = mSpUtils.getValue("mobile", "")
        mTime = mSpUtils.getValue("time", 0L)
        mCode = mSpUtils.getValue("code", "")
        // 手机号码
        login_mobile.setText(mMobile)
        // 时间判断
        val time = (System.currentTimeMillis() - mTime) / 1000
        if (mTime != 0L && time < 60) {
            login_code_get.text = "${60 - time}s后重新获取"
            login_code_get.isEnabled = false
            mCountDownHandler.start()
        }
    }

    fun loginCodeBtnClick(v: View) {
        if (NoFastClickUtils.isFastClick()) return
        when (v) {
            login_code_get -> /*获取验证码*/ {
                if (!login_policy_agree.isSelected) {
                    showNormalTip(topBar, "请阅读并同意隐私政策和用户协议")
                    return
                }
                mMobile = login_mobile.text.toString()
                if (mMobile.isEmpty()) {
                    showNormalTip(topBar, "请输入手机号码")
                    return
                }
                if (mMobile.length != 11) {
                    showNormalTip(topBar, "手机号码有误")
                    return
                }
                getCode()
            }
            login_huawei -> /*华为账号登录*/ huaweiLogin()
            login_wechat -> /*微信一键登录*/ wechatLogin()
            login_password -> /*密码登录*/ {
                val intent = Intent(mContext, LoginPasswordActivity::class.java)
                intent.putExtra(LoginConfig.paramsIsBuy, mIsBuy)
                mOtherLogin.launch(intent)
            }
            login -> /*登录*/ loginCode()
            login_privacy_policy -> /*隐私政策*/ {
                PrivacyActivity.showRule(mContext, PrivacyActivity.ShowPolicy)
            }
            login_user_agreement -> /*用户协议*/ {
                PrivacyActivity.showRule(mContext, PrivacyActivity.ShowUserAgreement)
            }
            login_policy -> /* 勾选隐私政策和用户协议 */ {
                login_policy_agree.isSelected = !login_policy_agree.isSelected
                if (login_policy_agree.isSelected) {
                    login_policy_agree.setImageResource(R.mipmap.login_checkbox_sel)
                } else {
                    login_policy_agree.setImageResource(R.mipmap.login_checkbox_nor)
                }
            }
        }
    }

    private fun getCode() {
        showLoading("正在获取验证码")
        // 随机数（最大长度128个字符）
        val nonce = "${(Random.nextDouble() * (999999 - 100000 + 1) + 100000).toInt()}"
        // 当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
        val curTime = "${System.currentTimeMillis() / 1000L}"
        // SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，
        // 进行SHA1哈希计算，转化成16进制字符(String，小写)
        val checkSum = MD5Util.getCheckSum(getString(R.string.CodeAppSecret), nonce, curTime)
        RxHttp.postForm("https://api.netease.im/sms/sendcode.action")
            .addHeader("AppKey", getString(R.string.CodeAppKey))
            .addHeader("Nonce", nonce)
            .addHeader("CurTime", curTime)
            .addHeader("CheckSum", checkSum)
            .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
            .add("templateid", getString(R.string.CodeTemplateId))
            .add("mobile", mMobile)
            .add("codeLen", LoginConfig.CodeLen)
            .asClass(CodeLoginModel::class.java)
            .to(RxLife.toMain(this))
            .subscribe({
                hideLoading()
                if (it.code == ApiConfig.SUCCESSCODE) {
                    showSuccessTip(topBar, "验证码已发送")
                    mCode = it.obj
                    mTime = System.currentTimeMillis()
                    login_code_get.text = "60s后重新获取"
                    login_code_get.isEnabled = false
                    mCountDownHandler.start()

                    mSpUtils.putValue("time", mTime)
                    mSpUtils.putValue("code", mCode)
                    mSpUtils.putValue("mobile", mMobile)
                } else {
                    showNormalTip(topBar, it.desc.ifEmpty { it.msg })
                }
            }, {
                hideLoading()
                showNormalTip(topBar, "网络异常，请重试！")
            })
    }

    private fun loginCode() {
        if (!login_policy_agree.isSelected) {
            showNormalTip(topBar, "请阅读并同意隐私政策和用户协议")
            return
        }
        val mobile = login_mobile.text.toString()
        if (mobile.isEmpty()) {
            showNormalTip(topBar, "请输入手机号码")
            return
        }
        if (mobile.length != 11) {
            showNormalTip(topBar, "手机号码有误")
            return
        }
        val code = login_code.text.toString()
        if (code.isEmpty()) {
            showNormalTip(topBar, "请输入短信验证码")
            return
        }
        if (mCode != code || mMobile != mobile) {
            showSuccessTip(topBar, "验证码错误")
            return
        }
        showLoading("正在登录")
        register(mobile, mobile, mobile, UserManager.LoginType_code)
    }

    override fun getTopBar(): QMUITopBarLayout = topBar

    override fun loginSuccess() {
        mSpUtils.putValue("time", 0L)
        mSpUtils.putValue("code", "")
    }

    override fun onDestroy() {
        mCountDownHandler.stop()
        super.onDestroy()
    }
}
